<?php
namespace app\wechat\controller;
use think\Cache;
use think\Controller;
use Yansongda\Pay\Pay;
use workerman\Gateway;

/**
 * 回调控制器类
 *
 */
class Callback extends Controller
{
    public function _initialize() {
        parent::_initialize();
    }

    //执行回调
    public function excute() {
    	$params = $this->request->param();
        $uuid = $params['state'];
        $state = Cache::store('redis')->get('wechat:auth:'.$uuid);
        if (!$state) return false;
        list($url,$params['live_id'],$params['sid'],$params['openid'],$params['user_name'],$params['own_type']) = explode(',', $state);
		list($module, $controller, $action) = explode('-', $url);
        $redirect_uri = url(DS .$module. DS .$controller. DS .$action, $params, false, true);
    	$this->redirect($redirect_uri);
    }

    public function ticket() {
        model('wechat/open','service')->ticket();
        die('success');
    }

    public function event() {
        model('wechat/open', 'service')->events();
    }

    /* 微信扫码支付回调 */
    public function notify() {
        $request = (array) simplexml_load_string($this->request->getInput(), 'SimpleXMLElement', LIBXML_NOCDATA);
        if (!$request) return;

        $cache = cache('wechat_pay'.$request['out_trade_no'],'',['path'=>RUNTIME_PATH.'/wechat_pay']);
        $auth = model('wechat/open_auth','service')->get(['user_name'=>$cache['user_name']]);
        if (!$auth) return;

        $config = [];
        $config['wechat']['app_id'] = $auth['appid'];   // 微信公众号 APPID
        $config['wechat']['mch_id'] = $auth['mch_id'];  // 微信商户号
        $config['wechat']['key']    = $auth['key'];     // 微信支付签名秘钥
        $config['wechat']['notify_url'] = url('/wechat/callback/notify',[],false,true);//异步通知地址
        $config['wechat']['cert_client']= '';           // 客户端证书路径，退款时需要用到
        $config['wechat']['cert_key']   = '';           // 客户端秘钥路径，退款时需要用到

        $lib_pay = new Pay($config);
        $verify = $lib_pay->driver('wechat')->gateway($cache['type'])->verify($this->request->getInput());
        if (!$verify) return;

        $userInfo = model('wechat/open', 'service')->getUserInfo($request['openid']);

        $data = [];
        $data['openid']     = $request['openid'];
        $data['nickname']   = (string) $userInfo['nickname'];
        $data['headimgurl'] = (string) $userInfo['headimgurl'];
        $data['money']      = decimal($request['total_fee']/100);
        $data['event']      = $cache['event'];
        $data['method']     = 'wechat';
        $data['trade_no']   = $request['out_trade_no'];
        $data['payment_no'] = $request['transaction_id'];
        $data['paytime']    = strtotime($request['time_end']);

        switch ($cache['event']) {
            case 'shakearound_apply':   // 摇一摇设备申请
                $apply = model('wechat/shakearound_apply', 'service')->get(['pay_sn'=>$request['out_trade_no']]);
                if (!$apply) {
                    return;
                }
                $result = model('wechat/shakearound_apply', 'service')->save(['pay_time'=>time()],['pay_sn'=>$request['out_trade_no']]);
                if (!$result) {
                    return;
                }
                $data['remark'] = $cache['remark'] ? : '摇一摇设备申请';
                break;

            case 'auth_recharge':   // 公众号（鉴权号）账户充值
                $data['remark'] = $cache['remark'] ? : '公众号（鉴权号）账户充值';
                break;

            case 'red_recharge':    // 现场 - 抢红包充值
                $live_id = hashids($cache['identify'], 'decode');
                if ($live_id < 1) {
                    return;
                }
                $live = model('live/live', 'service')->fetch_by_id($live_id);
                if (!$live) {
                    return;
                }

                // 更新抢红包总金额
                $actives = $live['actives'];
                $actives['red_packet']['total_money'] = decimal($actives['red_packet']['total_money'] + $data['money'] / 1.02);
                $result = model('live/live', 'service')->manage($live, $actives);
                if ($result === false) {
                    return;
                }

                // 财务记录数据
                $data['live_id'] = $live_id;
                $data['live_name'] = $live['name'];
                $data['remark'] = $cache['remark'] ? : '现场 - 抢红包充值';
                $data['money_service'] = decimal($data['money'] - $data['money'] / 1.02);

                break;

            default :
                break;
        }

        $result = model('admin/finance', 'service')->save($data);
        if (!$result) return;

        // 当为 现场 抢红包 余额充值时，消息中间件推送
        if ($cache['event'] == 'red_recharge') {
            if ((int) Gateway::getClientCountByGroup($cache['identify']) > 0) {
                $result = [];
                $result['event']     = 'red_recharge';
                $result['action']    = 'recharge';
                $result['total_fee'] = decimal($data['money'] - $data['money_service']);
                Gateway::sendToGroup($cache['identify'], json_encode([$result]));
            }
        }

        // 干掉缓存
        cache('wechat_pay'.$request['out_trade_no'],null,['path'=>RUNTIME_PATH.'/wechat_pay']);

        // 返回微信服务器
        echo "success";
    }
}